package com.oa.controller;

import com.oa.back.ResponseBack;
import com.oa.common.annotion.Interceptor;
import com.oa.common.base.Pageable;
import com.oa.common.enums.*;
import com.oa.service.FlowService;
import com.oa.service.FormService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/manage/flow")
public class FlowController extends BaseController {

    private static final Logger logger= LoggerFactory.getLogger(FlowController.class);

    @Autowired
    private FlowService flowService;

    @Autowired
    private FormService formService;

    @RequestMapping(value = "index.html",method = RequestMethod.GET)
    public String index(ModelMap modelMap, String key, Long typeId, Pageable pageable){
        modelMap.addAttribute("key",key);
        modelMap.addAttribute("typeId",typeId);
        modelMap.addAttribute("page",flowService.findPage(pageable,key,typeId));
        modelMap.addAttribute("pageable",pageable);
        return "/admin/flow/index";
    }

    @RequestMapping(value = "add.html",method = RequestMethod.GET)
    public String add(ModelMap modelMap,Long typeId){
        modelMap.addAttribute("typeId",typeId);
        modelMap.addAttribute("types",FlowType.values());
        modelMap.addAttribute("flows",flowService.find(typeId));
        modelMap.addAttribute("statuses",FlowStatus.values());
        modelMap.addAttribute("forms",formService.find(typeId));
        modelMap.addAttribute("auditTypes", AuditType.values());
        modelMap.addAttribute("fileTypes",FlowFileType.values());
        modelMap.addAttribute("dataTypes", DateType.values());
        return "/admin/flow/add";
    }

    @RequestMapping(value = "submit",method = RequestMethod.POST)
    @ResponseBody
    @Interceptor(actionName = "提交流程的接口")
    public ResponseBack<String> submit(String params){
        try{
            return flowService.submit(params);
        }catch (RuntimeException ex){
            logger.error("提交流程接口的异常:",ex);
            return ResponseBack.fial(CodeStatus.SYSTEM_FAIL.getResponseStatus());
        }
    }

    @RequestMapping(value = "validate",method = RequestMethod.GET)
    @ResponseBody
    @Interceptor(actionName = "校验流程的接口")
    public Boolean validate(String name,Long typeId,Long id){
        return !flowService.validate(name,typeId,id);
    }
}
